package cn.yj.common;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import net.glxn.qrgen.core.image.ImageType;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;

/**
 * <br>
 *
 * @author 永健
 * @since 2020-07-02 17:51
 */
public class QrUtils {
    public static ByteArrayOutputStream createLinkQrCode(String url, Map<String, String> params) throws IOException,
            WriterException {
        //设置二维码url链接，图片宽度250*250，JPG类型
        return createQrGen(url, params);
    }

    public static ByteArrayOutputStream createQrGen(String content) throws IOException, WriterException {
        //设置二维码url链接，图片宽度250*250，JPG类型
        return createQrGen(content, null);
    }

    private static ByteArrayOutputStream createQrGen(String url, Map<String, String> params) throws IOException, WriterException {
        // 设置二维码url链接，图片宽度250*250，JPG类型
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(installUrl(url, params), BarcodeFormat.QR_CODE, 250, 250);
        // 去除白边
        bitMatrix=deleteWhite(bitMatrix);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, ImageType.JPG.name(), stream);
        return stream;
    }

    private static String installUrl(String url, Map<String, String> params) {
        StringBuffer buffer = new StringBuffer();
        buffer.append(url);

        if (params != null) {
            if (url.indexOf("?") >= 0) {
                buffer.append("&");
            } else {
                buffer.append("?");
            }
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String key = entry.getKey();
                Object val = entry.getValue();
                if (val != null) {
                    String value = entry.getValue().toString();
                    buffer.append(key + "=" + value + "&");
                }
            }
        } else {
            return url;
        }

        return buffer.toString().substring(0, buffer.length() - 1);
    }

    private static BitMatrix deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1]))
                    resMatrix.set(i, j);
            }
        }
        return resMatrix;
    }
}
